package com.yuanmei.stockeyes.activities;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import com.yuanmei.stockeyes.R;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.graphics.Color;
import android.graphics.PointF;
import android.view.MotionEvent;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.app.AlertDialog;

import cn.limc.androidcharts.common.IDataCursor;
import cn.limc.androidcharts.entity.DateValueEntity;
import cn.limc.androidcharts.entity.IStickEntity;
import cn.limc.androidcharts.entity.LineEntity;
import cn.limc.androidcharts.entity.ListChartData;
import cn.limc.androidcharts.entity.OHLCEntity;
import cn.limc.androidcharts.view.BOLLMASlipCandleStickChart;
import cn.limc.androidcharts.event.IDisplayCursorListener;

import com.yuanmei.stockeyes.artifacts.Extensions;
import com.yuanmei.stockeyes.data.DataProvider;
import com.yuanmei.stockeyes.data.HistoryQuotesDataBase.HistoryRecord;
import com.yuanmei.stockeyes.model.Stock;
import com.tictactec.ta.lib.Core;
import com.tictactec.ta.lib.MAType;
import com.tictactec.ta.lib.MInteger;
import com.tictactec.ta.lib.RetCode;

import financedata.historicalquotes.Interval;
import info.hoang8f.android.segmented.SegmentedGroup;

import com.yuanmei.stockeyes.charts.ITalibChart;
import com.yuanmei.stockeyes.charts.TalibChartFactory;

public class StockAnalysisActivity extends Activity implements OnClickListener, DataProvider.AsyncDownloadCallback {
    // Intent parms
    public  final static String ANALYSIS_CODE="analysis_code";
    public  final static String ANALYSIS_INTERVAL="analysis_interval";

    public  final static int DEFALUT_DISPLAY_NUMBER = 60;

    private BOLLMASlipCandleStickChart  mMainChart;
    private int mMainTaIndexBegin  = 0;
    private int mMainTaIndexNumber = 0;

    private FrameLayout  mStockMainFrame;
    private FrameLayout  mStockTaIndexFrame;
    private ImageView    mTaIndexRightBorder;
    private ImageView    mTaIndexLeftBorder;

    // Nav Bar
    private TextView mNavTitleName;
    private TextView mNavTitleCode;

    private SegmentedGroup mNavIntervalGroup;

    private RadioButton    mNavIntervalDayButton;
    private RadioButton    mNavIntervalWeekButton;
    private RadioButton    mNavIntervalMonthButton;

    private TextView mStockOpenText;
    private TextView mStockHighText;
    private TextView mStockDateText;
    private TextView mStockCloseText;
    private TextView mStockLowText;
    private TextView mStockVolumeText;
    private TextView mStockResultText;

    private TextView mStockMaDetailsText;
    private TextView mStockBollDetailsText;

    private TextView mTaIndexShortName;
    private TextView mTaIndexDetail;
    private TextView mTaIndexParm;

    private StockTachartCursorListener mTaChartCursorListener = new StockTachartCursorListener(false);
    private StockTachartTouchListener  mTaChartTouchListener  = new StockTachartTouchListener();

    private ImageView mMainFrameAnimateImage;
    private ImageView mTaIndexFrameAnimateImage;
    private Animation mMainDownloadingAnimation;
    private Animation mIndexDownloadingAnimation;

    private String              mCurrStockCode;
    private Stock               mCurrStock;
    private Interval            mCurrentInterval = Interval.DAILY;
    private List<HistoryRecord> mCurrHisRecs;
    private int                 mCurrHisIndex;

    private List<IStickEntity> mCurrCandleStickList = new ArrayList<IStickEntity>();
    private double  mCurrMaxPrice, mCurrMinPrice;
    private int     mCurrCloseDataLen;

    private float[] mCurrOpenPrices;
    private float[] mCurrHighPrices;
    private float[] mCurrLowPrices;
    private float[] mCurrClosePrices;
    private float[] mCurrVolumes;
    private float[] mCurrAmounts;
    private int[]   mCurrDates;

    //private final List<ITalibChart>   mTalibChartLists = new LinkedList<ITalibChart>();
    private List<ITalibChart>   mTalibChartLists;
    private int                 mTalibChartIndex = -1;

    private final Core mTaLibCore = new Core();

    LineEntity<DateValueEntity> mSmaShortLine;
    LineEntity<DateValueEntity> mSmaMediumLine;
    LineEntity<DateValueEntity> mSmaLongLine;
    LineEntity<DateValueEntity> mSmaLongestLine;
    LineEntity<DateValueEntity> mSmaMA60Line;
    LineEntity<DateValueEntity> mSmaMA90Line;
//    LineEntity<DateValueEntity> mSmaMA240Line;
    List<LineEntity<DateValueEntity>> mSMALines = new ArrayList<LineEntity<DateValueEntity>>();
    private static final String TAG = "StockAnalysis";

    private AlphaAnimation mBorderFlashAnimation;
    private class BorderAnimationListener implements AnimationListener{

        @Override
        public void onAnimationEnd(Animation animation) {
            mTaIndexRightBorder.setVisibility(View.INVISIBLE);
            mTaIndexRightBorder.invalidate();
            mTaIndexRightBorder.setAnimation(null);

            mTaIndexLeftBorder.setVisibility(View.INVISIBLE);
            mTaIndexLeftBorder.invalidate();
            mTaIndexLeftBorder.setAnimation(null);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationStart(Animation animation) {
        }

    }

    public class StockTachartTouchListener implements OnTouchListener {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return doGestureDetecting(v, event);
        }
    }

    private boolean mIsShowTouchLine = false;
    private boolean isShowTouchLine() {
        return mIsShowTouchLine;
    }
    private void hideTouchLine() {
        mMainChart.setDisplayCrossXOnTouch(false);
        getCurrTaChart().setDisplayCrossXOnTouch(false);
        mMainChart.postInvalidate();
        getCurrTaChart().postInvalidate();
        mIsShowTouchLine = false;
    }

    private void showTouchLine() {
        mMainChart.setDisplayCrossXOnTouch(true);
        getCurrTaChart().setDisplayCrossXOnTouch(true);
        mMainChart.postInvalidate();
        getCurrTaChart().postInvalidate();
        mIsShowTouchLine = true;
    }

    private PointF mSingleTouchPoint   = new PointF();
    private long   mLastMoveTimeMillis = 0;
    private static final int TOUCH_MOVE_MIN_DISTANCE = 6;
    private synchronized boolean doGestureDetecting(View v, MotionEvent event) {

        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                if (event.getPointerCount() == 1) {
                    mSingleTouchPoint.set(event.getX(), event.getY());
                }
                break;
            case MotionEvent.ACTION_UP:
                if (event.getPointerCount() == 1) {
                    mSingleTouchPoint.set(event.getX(), event.getY());
                }
                break;
            case MotionEvent.ACTION_MOVE:
                // single touch point moved
                if (event.getPointerCount() == 1) {
                    float moveXdistance = Math.abs(event.getX() - mSingleTouchPoint.x);
                    //float moveYdistance = Math.abs(event.getY() - mSingleTouchPoint.y);
                    if (moveXdistance > TOUCH_MOVE_MIN_DISTANCE) {
                        double changeX = Math.floor(event.getX() - mSingleTouchPoint.x);
                        int step = (int) (changeX / TOUCH_MOVE_MIN_DISTANCE);
                        chartVisibleChanged(mCurrDisplayFrom - step, mCurrDisplayNumer, true);
                        mSingleTouchPoint.set(event.getX(), event.getY());
                        hideTouchLine();
                        mLastMoveTimeMillis = System.currentTimeMillis();
                        return true;
                    }
                }
                break;
        }
        return false;
    }

    public class StockTachartCursorListener implements IDisplayCursorListener {

        private boolean mIsListenMainChart;

        StockTachartCursorListener(boolean isMain) {
            mIsListenMainChart = isMain;
        }

        public void onCursorChanged(IDataCursor dataCursor, int displayFrom,
                int displayNumber) {
            chartVisibleChanged(displayFrom, displayNumber, true);
        }

        public void onTouchCursorChanged(PointF newPoint) {
            if (mIsListenMainChart) {
                ITalibChart ta_chart = getCurrTaChart();
                PointF syncTouchPoint = new PointF(newPoint.x,
                        ta_chart.getValidMiddleY());
                ta_chart.setTouchPoint(syncTouchPoint);
                ta_chart.postInvalidate();
            } else {
                PointF syncTouchPoint = new PointF(newPoint.x,
                        mMainChart.getValidMiddleY());
                mMainChart.setTouchPoint(syncTouchPoint);
                mMainChart.postInvalidate();
            }

            if ((System.currentTimeMillis() - mLastMoveTimeMillis) > 500) {
                showTouchLine();
                mCurrHisIndex = mCurrHisRecs.size() - 1 - mMainChart.getSelectedIndex();
                flushStockQutoesTextView();
                flushTaIndexTextView();
            }
        }
    }

    private int mCurrDisplayNumer = 60;
    private int mCurrDisplayFrom  = 0;
    private synchronized void chartVisibleChanged(int displayFrom, int displayNumber, boolean isAnimal) {
        if (mMainTaIndexNumber <= 0)  {
            return;
        }

        if (displayNumber < 5) {
            displayNumber = 5;
        }

        ITalibChart ta_chart = getCurrTaChart();

        boolean isLeftOver  = false;
        boolean isRightOver = false;
        int validBegin = Math.max(mMainTaIndexBegin, ta_chart.getTaIndexBegin());
        if (displayFrom < validBegin) {
            Log.d(TAG, "chartVisibleChanged LeftOver validBegin=" + validBegin + " displayFrom=" + displayFrom);
            displayFrom = validBegin;
            isLeftOver = true;
        }

        int lastNumber = displayFrom + displayNumber;
        int validLast  = Math.min((mMainTaIndexBegin + mMainTaIndexNumber),
                                 (ta_chart.getTaIndexBegin() + ta_chart.getTaIndexNumber()));
        if (lastNumber > validLast) {
            Log.d(TAG, "chartVisibleChanged rightOver lastNumber=" + lastNumber
                    + " validLast=" + validLast);
            lastNumber = validLast;
            isRightOver = true;
        }

        displayFrom = lastNumber - displayNumber;

        mCurrDisplayFrom  = displayFrom;
        mCurrDisplayNumer = displayNumber;

        mMainChart.setDisplayFrom(mCurrDisplayFrom);
        mMainChart.setDisplayNumber(mCurrDisplayNumer);
        ta_chart.setDisplayFrom(mCurrDisplayFrom);
        ta_chart.setDisplayNumber(mCurrDisplayNumer);
        mMainChart.postInvalidate();
        ta_chart.postInvalidate();

        if (isAnimal && (isLeftOver || isRightOver)) {
            if (isLeftOver) {
                mTaIndexLeftBorder.setVisibility(View.VISIBLE);
                mTaIndexLeftBorder.setAnimation(mBorderFlashAnimation);
            }
            if (isRightOver) {
                mTaIndexRightBorder.setVisibility(View.VISIBLE);
                mTaIndexRightBorder.setAnimation(mBorderFlashAnimation);
            }
            mBorderFlashAnimation.startNow();

            mTaIndexRightBorder.invalidate();
            mTaIndexLeftBorder.invalidate();
        }
    }

    private LineEntity<DateValueEntity> calcSmaLine(List<IStickEntity> ohlcLists,
            int period, int color) {

        if (period < 2) {
            return null;
        }

        List<DateValueEntity> SMAValues = new ArrayList<DateValueEntity>();
        float sum = 0;
        float avg = 0;
        for (int i = 0; i < ohlcLists.size() ; i++) {
            float close = (float) ((OHLCEntity) ohlcLists.get(i)).getClose();
            if (i < period) {
                sum = sum + close;
                avg = sum / (i + 1f);
            } else {
                sum = sum + close -
                        (float) ((OHLCEntity) ohlcLists.get(i - period)).getClose();
                avg = sum / period;
            }
            SMAValues.add(new DateValueEntity((float)avg, ohlcLists.get(i).getDate()));
        }

        LineEntity<DateValueEntity> smaLine = new LineEntity<DateValueEntity>();
        smaLine.setTitle("MA" + period);
        smaLine.setLineColor(color);

        smaLine.setLineData(SMAValues);
        return smaLine;
    }

    private void rebuildHisDataSets(List<HistoryRecord> hisRecs) {

        mCurrCloseDataLen = hisRecs.size();
        mCurrOpenPrices   = new float[mCurrCloseDataLen];
        mCurrHighPrices   = new float[mCurrCloseDataLen];
        mCurrLowPrices    = new float[mCurrCloseDataLen];
        mCurrClosePrices  = new float[mCurrCloseDataLen];
        mCurrVolumes      = new float[mCurrCloseDataLen];
        mCurrAmounts      = new float[mCurrCloseDataLen];
        mCurrDates   = new int[mCurrCloseDataLen];

        mCurrCandleStickList.clear();
        mCurrMaxPrice = Double.MIN_VALUE;
        mCurrMinPrice = Double.MAX_VALUE;

        int r_idx = 0;
        for (int i = hisRecs.size() - 1; i >= 0; i--) {
            HistoryRecord rec = hisRecs.get(i);
            mCurrCandleStickList.add(new OHLCEntity(rec.mOpen, rec.mHigh,
                    rec.mLow, rec.mClose, (int) rec.mDate));
            if (rec.mHigh > mCurrMaxPrice) {
                mCurrMaxPrice = rec.mHigh;
            }
            if (rec.mLow < mCurrMinPrice) {
                mCurrMinPrice = rec.mLow;
            }
            mCurrVolumes[r_idx]     = rec.mVolume;
            mCurrAmounts[r_idx]     = rec.mAmount;
            mCurrOpenPrices[r_idx]  = rec.mOpen;
            mCurrHighPrices[r_idx]  = rec.mHigh;
            mCurrLowPrices[r_idx]   = rec.mLow;
            mCurrClosePrices[r_idx] = rec.mClose;
            mCurrDates[r_idx]  = (int) rec.mDate;
            r_idx++;
        }
    }

    // Main chart TaIndex param's func
    private int mSmaShortPeriod    = 5;
    private int mSmaMediumPeriod   = 10;
    private int mSmaLongPeriod     = 20;
    private int mSmaLongestPeriod  = 30;
    private String mSmaShortPeriodName;
    private String mSmaMediumPeriodName;
    private String mSmaLongPeriodName;
    private String mSmaLongestPeriodName;

    private List<Map<String, Object>> getSmaParamsList() {

        List<Map<String, Object>> outParamsList = new ArrayList<Map<String, Object>>();
        Map<String, Object> item = new HashMap<String, Object>();
        item.put(ITalibChart.ITaParamNameKey,  mSmaShortPeriodName);
        item.put(ITalibChart.ITaParamValueKey, mSmaShortPeriod);
        outParamsList.add(item);

        item = new HashMap<String, Object>();
        item.put(ITalibChart.ITaParamNameKey,  mSmaMediumPeriodName);
        item.put(ITalibChart.ITaParamValueKey, mSmaMediumPeriod);
        outParamsList.add(item);

        item = new HashMap<String, Object>();
        item.put(ITalibChart.ITaParamNameKey,  mSmaLongPeriodName);
        item.put(ITalibChart.ITaParamValueKey, mSmaLongPeriod);
        outParamsList.add(item);

        item = new HashMap<String, Object>();
        item.put(ITalibChart.ITaParamNameKey,  mSmaLongestPeriodName);
        item.put(ITalibChart.ITaParamValueKey, mSmaLongestPeriod);
        outParamsList.add(item);

        return outParamsList;
    }

    private void setSmaParamsList(Hashtable<String, Integer> inParamMaps) {
        if (inParamMaps.containsKey(mSmaShortPeriodName)
                && inParamMaps.containsKey(mSmaMediumPeriodName)
                && inParamMaps.containsKey(mSmaLongPeriodName)
                && inParamMaps.containsKey(mSmaLongestPeriodName)
                ) {
            mSmaShortPeriod   = inParamMaps.get(mSmaShortPeriodName);
            mSmaMediumPeriod  = inParamMaps.get(mSmaMediumPeriodName);
            mSmaLongPeriod    = inParamMaps.get(mSmaLongPeriodName);
            mSmaLongestPeriod = inParamMaps.get(mSmaLongestPeriodName);
        }
    }

    public Spanned getSmaDetail() {
        if (null == mSMALines) {
            return new SpannableString("----");
        }

        int index = mMainChart.getSelectedIndex();

        String smaShortText = String.format(Locale.ENGLISH, "MA%d:%.2f ",
                mSmaShortPeriod,
                mSmaShortLine.getLineData().get(index).getValue());
        String smaMediumText = String.format(Locale.ENGLISH, "MA%d:%.2f ",
                mSmaMediumPeriod,
                mSmaMediumLine.getLineData().get(index).getValue());
        String smaLongText = String.format(Locale.ENGLISH, "MA%d:%.2f ",
                mSmaLongPeriod,
                mSmaLongLine.getLineData().get(index).getValue());
        String smaLongestText = String.format(Locale.ENGLISH, "MA%d:%.2f",
                mSmaLongestPeriod,
                mSmaLongestLine.getLineData().get(index).getValue());

        String smaMa60Text = String.format(Locale.ENGLISH, "MA60:%.2f ",
                mSmaMA60Line.getLineData().get(index).getValue());
        String smaMa90Text = String.format(Locale.ENGLISH, "MA90:%.2f ",
                mSmaMA90Line.getLineData().get(index).getValue());
//        String smaMa240Text = String.format(Locale.ENGLISH, "MA240:%.2f ",
//                mSmaMA240Line.getLineData().get(index).getValue());


        String finalString = smaShortText + smaMediumText + smaLongText + smaLongestText
                    + smaMa60Text + smaMa90Text;
        Spannable sb = new SpannableString(finalString);
        sb.setSpan(new ForegroundColorSpan(mSmaShortLine.getLineColor()),
                finalString.indexOf(smaShortText),
                finalString.indexOf(smaShortText) + smaShortText.length(),
                Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        sb.setSpan(new ForegroundColorSpan(mSmaMediumLine.getLineColor()),
                finalString.indexOf(smaMediumText),
                finalString.indexOf(smaMediumText) + smaMediumText.length(),
                Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        sb.setSpan(new ForegroundColorSpan(mSmaLongLine.getLineColor()),
                finalString.indexOf(smaLongText),
                finalString.indexOf(smaLongText) + smaLongText.length(),
                Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        sb.setSpan(new ForegroundColorSpan(mSmaLongestLine.getLineColor()),
                finalString.indexOf(smaLongestText),
                finalString.indexOf(smaLongestText) + smaLongestText.length(),
                Spanned.SPAN_EXCLUSIVE_INCLUSIVE);

        sb.setSpan(new ForegroundColorSpan(mSmaMA60Line.getLineColor()),
                finalString.indexOf(smaMa60Text),
                finalString.indexOf(smaMa60Text) + smaMa60Text.length(),
                Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        sb.setSpan(new ForegroundColorSpan(mSmaMA90Line.getLineColor()),
                finalString.indexOf(smaMa90Text),
                finalString.indexOf(smaMa90Text) + smaMa90Text.length(),
                Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
//        sb.setSpan(new ForegroundColorSpan(mSmaMA240Line.getLineColor()),
//                finalString.indexOf(smaMa240Text),
//                finalString.indexOf(smaMa240Text) + smaMa240Text.length(),
//                Spanned.SPAN_EXCLUSIVE_INCLUSIVE);

        return (sb);
    }

    private int mBollbandMidmaPeriod        = 5;
    private int mBollbandUpSTDEVMultiple    = 4;
    private int mBollbandDownSTDEVMultiple  = 4;

    private String mBollbandMidmaPeriodName;
    private String mBollbandUpSTDEVMultipleName;
    private String mBollbandDownSTDEVMultipleName;

    private List<Map<String, Object>> getBollbandParamsList() {

        List<Map<String, Object>> outParamsList = new ArrayList<Map<String, Object>>();
        Map<String, Object> item = new HashMap<String, Object>();
        item.put(ITalibChart.ITaParamNameKey,  mBollbandMidmaPeriodName);
        item.put(ITalibChart.ITaParamValueKey, mBollbandMidmaPeriod);
        outParamsList.add(item);

        item = new HashMap<String, Object>();
        item.put(ITalibChart.ITaParamNameKey,  mBollbandUpSTDEVMultipleName);
        item.put(ITalibChart.ITaParamValueKey, mBollbandUpSTDEVMultiple);
        outParamsList.add(item);

        item = new HashMap<String, Object>();
        item.put(ITalibChart.ITaParamNameKey,  mBollbandDownSTDEVMultipleName);
        item.put(ITalibChart.ITaParamValueKey, mBollbandDownSTDEVMultiple);
        outParamsList.add(item);

        return outParamsList;
    }

    private void setBollbandParamsList(Hashtable<String, Integer> inParamMaps) {
        if (inParamMaps.containsKey(mBollbandMidmaPeriodName)
                && inParamMaps.containsKey(mBollbandUpSTDEVMultipleName)
                && inParamMaps.containsKey(mBollbandDownSTDEVMultipleName)
                ) {
            mBollbandMidmaPeriod       = inParamMaps.get(mBollbandMidmaPeriodName);
            mBollbandUpSTDEVMultiple   = inParamMaps.get(mBollbandUpSTDEVMultipleName);
            mBollbandDownSTDEVMultiple = inParamMaps.get(mBollbandDownSTDEVMultipleName);
        }
    }

    private Spanned getBollbandDetail() {
        if (null == mBollbandLowLine || null == mBollbandLowLine) {
            return new SpannableString("----");
        }

        int index = mMainChart.getSelectedIndex();
        String  bbandUpText = String.format(Locale.ENGLISH, "%s:%.2f ",
                getString(R.string.param_bband_up_description),
                mBollbandUpLine.getLineData().get(index).getValue());
        String  bbandLowText = String.format(Locale.ENGLISH, "%s:%.2f ",
                getString(R.string.param_bband_low_description),
                mBollbandLowLine.getLineData().get(index).getValue());

        String    finalString = bbandUpText + bbandLowText;
        Spannable sb          = new SpannableString(finalString);
        sb.setSpan(new ForegroundColorSpan(mBollbandUpLine.getLineColor()),
                finalString.indexOf(bbandUpText),
                finalString.indexOf(bbandUpText) + bbandUpText.length(),
                Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        sb.setSpan(new ForegroundColorSpan(mBollbandLowLine.getLineColor()),
                finalString.indexOf(bbandLowText),
                finalString.indexOf(bbandLowText) + bbandLowText.length(),
                Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        return (sb);
    }

    private LineEntity<DateValueEntity> mBollbandLowLine;
    private LineEntity<DateValueEntity> mBollbandUpLine;
    private void rebuildMainChartData() {
        mSMALines.clear();

        mSmaShortLine   = calcSmaLine(mCurrCandleStickList, mSmaShortPeriod,  Color.WHITE);
        mSmaMediumLine  = calcSmaLine(mCurrCandleStickList, mSmaMediumPeriod, Color.YELLOW);
        mSmaLongLine    = calcSmaLine(mCurrCandleStickList, mSmaLongPeriod, Color.RED);
        mSmaLongestLine = calcSmaLine(mCurrCandleStickList, mSmaLongestPeriod, Color.GREEN);

        mSMALines.add(mSmaShortLine);
        mSMALines.add(mSmaMediumLine);
        mSMALines.add(mSmaLongLine);
        mSMALines.add(mSmaLongestLine);

        // 更多的均线
        Resources r = this.getResources();

        mSmaMA60Line = calcSmaLine(mCurrCandleStickList, 60,
                r.getColor(R.color.mediumslateblue));
        mSmaMA90Line = calcSmaLine(mCurrCandleStickList, 90,
                r.getColor(R.color.mediumturquoise));
//        mSmaMA240Line = calcSmaLine(mCurrCandleStickList, 240,
//                r.getColor(R.color.orange));
        mSMALines.add(mSmaMA60Line);
        mSMALines.add(mSmaMA90Line);
//        mSMALines.add(mSmaMA240Line);

        MInteger outBegIdx    = new MInteger();
        MInteger outNBElement = new MInteger();

        double[] outRealUpperBand    = new double[mCurrCloseDataLen];
        double[] outRealMiddleBand   = new double[mCurrCloseDataLen];
        double[] outRealLowerBand    = new double[mCurrCloseDataLen];
        RetCode retCode = mTaLibCore.bbands(0, mCurrClosePrices.length - 1, mCurrClosePrices,
                mBollbandMidmaPeriod, mBollbandUpSTDEVMultiple, mBollbandDownSTDEVMultiple, MAType.Sma,
                outBegIdx, outNBElement,
                outRealUpperBand, outRealMiddleBand, outRealLowerBand);
        if (retCode == RetCode.Success) {
            //Log.i(TAG, "DBG MainChart Output Begin:"  + outBegIdx.value +
            //        " NBElement:" + outNBElement.value);

            List<DateValueEntity> dv_low = new ArrayList<DateValueEntity>();
            List<DateValueEntity> dv_up  = new ArrayList<DateValueEntity>();
            for (int i = 0; i < mCurrCloseDataLen; i++) {
                if (i < outBegIdx.value) {
                    dv_low.add(new DateValueEntity((float)outRealLowerBand[0],
                            mCurrDates[i]));
                    dv_up.add(new DateValueEntity((float)outRealUpperBand[0],
                            mCurrDates[i]));
                } else if ((i >= outBegIdx.value) && (i < (outBegIdx.value + outNBElement.value))) {
                    dv_low.add(new DateValueEntity((float)outRealLowerBand[i - outBegIdx.value],
                            mCurrDates[i]));
                    dv_up.add(new DateValueEntity((float)outRealUpperBand[i - outBegIdx.value],
                            mCurrDates[i]));
                } else {
                    Log.e(TAG, "Error: Get invalid bbands i=" + i
                            + " Begin:"  + outBegIdx.value
                            + ", outNBElement=" + outNBElement.value );
                }
            }
            // add lower line
            List<LineEntity<DateValueEntity>> band = new ArrayList<LineEntity<DateValueEntity>>();
            mBollbandLowLine = new LineEntity<DateValueEntity>();
            mBollbandLowLine.setTitle("LOWER");
            mBollbandLowLine.setLineColor(Color.YELLOW);
            mBollbandLowLine.setLineData(dv_low);
            band.add(mBollbandLowLine);

            // add upper line
            mBollbandUpLine = new LineEntity<DateValueEntity>();
            mBollbandUpLine.setTitle("UPPER");
            mBollbandUpLine.setLineColor(Color.CYAN);
            mBollbandUpLine.setLineData(dv_up);
            band.add(mBollbandUpLine);

            // add band to main chart
//            mMainChart.setBandData(band);
        }

        mMainChart.setLinesData(mSMALines);
        mMainChart.setStickData(new ListChartData<IStickEntity>(mCurrCandleStickList));

        mMainTaIndexBegin  = outBegIdx.value;
        mMainTaIndexNumber = outNBElement.value;
    }

    private ITalibChart getCurrTaChart() {
        if ( (mTalibChartIndex < 0) || mTalibChartIndex > (mTalibChartLists.size() - 1)) {
            return null;
        }
        return mTalibChartLists.get(mTalibChartIndex);
    }

    private void setCurrTaChart(int index) {
        if ( (index < 0) || index >= (mTalibChartLists.size())) {
            return;
        }

        if (index == mTalibChartIndex) {
            return;
        }

        ITalibChart preChart = getCurrTaChart();
        if (null != preChart) {
            preChart.setOnDisplayCursorListener(null);
            preChart.setOnTouchListener(null);
        }

        mTalibChartIndex = index;
        ITalibChart currTaLibChart = getCurrTaChart();
        if (null != currTaLibChart) {
            currTaLibChart.setOnDisplayCursorListener(mTaChartCursorListener);
            currTaLibChart.setOnTouchListener(mTaChartTouchListener);
            // SYNC TOUCH POINT
            if (isShowTouchLine()) {
                PointF syncTouchPoint = new PointF(mMainChart.getTouchPoint().x,
                        currTaLibChart.getValidMiddleY());
                currTaLibChart.setTouchPoint(syncTouchPoint);
                showTouchLine();
            }
        }
    }

    private void finishAcitivity(String reason) {
        String toast_text = getResources().getString(R.string.analysis_finish_toast_prefix) + reason;
        Toast.makeText(this, toast_text,Toast.LENGTH_SHORT).show();
        finish();
    }

    @Override
    public void onDownloadOver() {
        Log.i(TAG, "Async hisupdate onDownloadOver enter");
        flushAllViewToCurrentData();
    }

    private void flushStockQutoesTextView() {
        HistoryRecord record = mCurrHisRecs.get(mCurrHisIndex);

        mStockOpenText.setText(Extensions.format(record.mOpen));
        mStockHighText.setText(Extensions.format(record.mHigh));
        mStockDateText.setText(Extensions.simpleFormatDateValue(record.mDate));
        mStockCloseText.setText(Extensions.format(record.mClose));
        mStockLowText.setText(Extensions.format(record.mLow));
        mStockVolumeText.setText(Extensions.fromVolumeToShortHand(record.mVolume));

        mStockResultText.setText(String.format("%.2f%%",
                ((record.mClose - record.mOpen)*100)/record.mOpen));

        mStockMaDetailsText.setText(getSmaDetail());
        mStockBollDetailsText.setText(getBollbandDetail());
    }

    private void flushTaIndexTextView() {
        ITalibChart currTaChart = getCurrTaChart();

        mTaIndexShortName.setText("" + currTaChart.getTaIndexShortName());
        mTaIndexDetail.setText(currTaChart.getTaIndexDetail());
        mTaIndexParm.setText("" + currTaChart.getTaIndexParms());
    }

    private void flushAllViewToCurrentData() {
        mNavTitleName.setText(mCurrStock.getName());
        String code = mCurrStock.getCode();
        if (code.startsWith("^"))
            code = code.substring(1);
        code = code.substring(2);
        mNavTitleCode.setText(code);

        FrameLayout.LayoutParams parm = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT);

        List<HistoryRecord> new_recs = DataProvider.getLastNumHisRecords(
                StockAnalysisActivity.this,
                mCurrStock.getCode(), mCurrentInterval, -1, true, this);
        if (null == new_recs) {

            mMainFrameAnimateImage.startAnimation(mMainDownloadingAnimation);
            mMainFrameAnimateImage.setVisibility(View.VISIBLE);
            mStockMainFrame.removeAllViewsInLayout();
            mStockMainFrame.addView(mMainFrameAnimateImage, parm);

            mTaIndexFrameAnimateImage.startAnimation(mIndexDownloadingAnimation);
            mTaIndexFrameAnimateImage.setVisibility(View.VISIBLE);
            mStockTaIndexFrame.removeAllViewsInLayout();
            mStockTaIndexFrame.addView(mTaIndexFrameAnimateImage, parm);

            mStockMainFrame.requestLayout();
            mStockTaIndexFrame.requestLayout();

            Toast toast = Toast.makeText(this,
                    R.string.downloading_notify,
                    Toast.LENGTH_LONG);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return;
        }

        mCurrHisRecs  = new_recs;
        mCurrHisIndex = 0;

        rebuildHisDataSets(mCurrHisRecs);
        rebuildMainChartData();
        ITalibChart currTaChart = getCurrTaChart();
        currTaChart.reloadData(mCurrCloseDataLen,
                mCurrOpenPrices,
                mCurrHighPrices,
                mCurrLowPrices,
                mCurrClosePrices,
                mCurrVolumes,
                mCurrAmounts,
                mCurrDates);
        int mainChartLastNumber = mMainTaIndexBegin + mMainTaIndexNumber;
        int taChartLastNumber = currTaChart.getTaIndexBegin() + currTaChart.getTaIndexNumber();

        int lastNumber = Math.min(mainChartLastNumber, taChartLastNumber);
        int displayRange = Math.min(currTaChart.getTaIndexNumber(), mMainTaIndexNumber);
        displayRange = Math.min(displayRange, DEFALUT_DISPLAY_NUMBER);
        int displayStart = lastNumber - displayRange;

        mMainFrameAnimateImage.clearAnimation();
        mMainFrameAnimateImage.setVisibility(View.GONE);
        mTaIndexFrameAnimateImage.clearAnimation();
        mTaIndexFrameAnimateImage.setVisibility(View.GONE);

        mStockMainFrame.removeAllViewsInLayout();
        mStockMainFrame.addView(mMainChart, parm);

        mStockTaIndexFrame.removeAllViewsInLayout();
        mStockTaIndexFrame.addView(currTaChart.getChartView(), parm);

        mStockMainFrame.requestLayout();
        mStockTaIndexFrame.requestLayout();

        chartVisibleChanged(displayStart, displayRange, false);

        flushStockQutoesTextView();
        flushTaIndexTextView();
    }

    private void navStockBackOrForward(int step) {
        int position = DataProvider.getWatchList(this).indexOf(mCurrStock);
        position = position + step;
        if (position >= DataProvider.getWatchList(this).size()) {
            position = 0;
        } else if (position < 0) {
            position = DataProvider.getWatchList(this).size() - 1;
        }
        mCurrStock = DataProvider.getWatchList(this).get(position);
        flushAllViewToCurrentData();
    }

    private void navStockBack() {
        navStockBackOrForward(-1);
    }

    private void navStockForward() {
        navStockBackOrForward(1);
    }

    private void navTaIndexBackOrForward(int step) {
        Log.i(TAG, "navTaIndexBackOrForward step=" + step
                + ", mTalibChartIndex=" + mTalibChartIndex
                + ", size=" + mTalibChartLists.size());
        int position = mTalibChartIndex + step;
        if (position >= mTalibChartLists.size()) {
            position = 0;
        } else if (position < 0) {
            position = mTalibChartLists.size() - 1;
        }
        Log.i(TAG, "navTaIndexBackOrForward new position=" + position);
        setCurrTaChart(position);
        flushAllViewToCurrentData();
    }

    private void navTaIndexBack() {
        navTaIndexBackOrForward(-1);
    }

    private void navTaIndexForward() {
        Log.i(TAG, "navTaIndexForward" );
        navTaIndexBackOrForward(1);
    }

    class TaParamListAdapter extends BaseAdapter {
        public class ParamValueWatcher implements TextWatcher {
            private int mPosition;

            ParamValueWatcher(int position) {
                mPosition = position;
            }

            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    try {
                        Integer newValue = Integer.parseInt(
                                s.toString());
                        mTaParmList.get(mPosition).put(ITalibChart.ITaParamValueKey, newValue.toString());
                    } catch (NumberFormatException e) {
                        Log.e(TAG, "paramName(" + mTaParmList.get(mPosition).get(ITalibChart.ITaParamNameKey)
                                + ") conatin invalid value" + s.toString());
                    }
                }
            }
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) { }
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) { }
        }

        private static final String TAG = "TaParamListAdapter";
        private final class ViewHolder{
            public TextView ParmName;
            public EditText ParmValue;
        }
        private List<ViewHolder>  mViewHolderList;
        List<Map<String, Object>> mTaParmList;

        private LayoutInflater mInflater;

        public TaParamListAdapter(Context context) {
            mInflater = LayoutInflater.from(context);
            mViewHolderList = new ArrayList<ViewHolder>();
            mTaParmList     = new ArrayList<Map<String, Object>>();
        }

        public void setTaIndexParamList(List<Map<String, Object>> inParamList) {
            mTaParmList = inParamList;
        }

        public Hashtable<String, Integer> getTaIndexParamMap() {
            Hashtable<String, Integer> nwParams = new Hashtable<String, Integer>();
//            for(ViewHolder holder : mViewHolderList) {
//                try {
//                    String   paramName  = holder.ParmName.getText().toString();
//                    Integer  newValue = Integer.parseInt(
//                            holder.ParmValue.getText().toString());
//                    nwParams.put(paramName, newValue);
//                } catch (NumberFormatException e) {
//                    Log.e(TAG, "paramName(" + holder.ParmName.getText().toString()
//                            + ") conatin invalid value" + holder.ParmValue.getText().toString());
//                }
//            }

            for (Map<String, Object> parmpair : mTaParmList) {
                try {
                    String paramName  = (String) parmpair.get(ITalibChart.ITaParamNameKey);
                    String paramValue =  parmpair.get(ITalibChart.ITaParamValueKey).toString();
                    nwParams.put(paramName, Integer.parseInt(paramValue));
                } catch (NumberFormatException e) {
                    Log.e(TAG, "paramName(" + parmpair.get(ITalibChart.ITaParamNameKey).toString()
                            + ") conatin invalid value" + parmpair.get(ITalibChart.ITaParamValueKey).toString());
                }
            }
            return nwParams;
        }

        @Override
        public int getCount() {
            return mTaParmList.size();
        }

        @Override
        public Object getItem(int position) {
            // Get the data item associated with the specified position in the data set.(获取数据集中与指定索引对应的数据项)
            return mTaParmList.get(position);
        }

        @Override
        public long getItemId(int position) {
            // Get the row id associated with the specified position in the list.(取在列表中与指定索引对应的行id)
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.taparam_item, null);
                holder = new ViewHolder();
                /**得到各个控件的对象*/
                holder.ParmName  = (TextView) convertView.findViewById(R.id.TaParamName);
                holder.ParmValue = (EditText) convertView.findViewById(R.id.TaParamValue);
                /**设置TextView显示的内容，即我们存放在动态数组中的数据*/
                holder.ParmName.setText(mTaParmList.get(position).get(ITalibChart.ITaParamNameKey).toString());
                holder.ParmValue.setText(mTaParmList.get(position).get(ITalibChart.ITaParamValueKey).toString());

                holder.ParmValue.addTextChangedListener(new ParamValueWatcher(position));

                convertView.setTag(holder);//绑定ViewHolder对象
                mViewHolderList.add(holder);
            } else {
                holder = (ViewHolder)convertView.getTag();//取出ViewHolder对象
            }
            return convertView;
        }
    }

    interface UpdateParamsCallBack {
        void update(Hashtable<String, Integer> inParamMaps);
    }

    private void startParamDialog(String taindexName,
                                  List<Map<String, Object>> inParamList,
                                  final UpdateParamsCallBack okCallback) {
//        View mTaParamLayout = getLayoutInflater().inflate(R.layout.taparams_dialog, null);
//        if(mTaParamLayout.getParent() != null) {
//            ((ViewGroup)mTaParamLayout.getParent()).removeView(mTaParamLayout);
//        }
//        ListView mTaParamListView = (ListView) mTaParamLayout.findViewById(R.id.TaParamsList);

        LinearLayout linearLayoutMain = new LinearLayout(this);//自定义一个布局文件
        linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
                ));
        linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
        ListView listView = new ListView(this);//this为获取当前的上下文
        listView.setFadingEdgeLength(0);

        final TaParamListAdapter adapter = new TaParamListAdapter(this);
        adapter.setTaIndexParamList(inParamList);
        listView.setAdapter(adapter);
        linearLayoutMain.addView(listView);

        String dialog_title = this.getString(R.string.params_diag_title_prefix)
                + " : " + taindexName;

        final AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle(dialog_title).setView(linearLayoutMain)
                .setPositiveButton(R.string.label_ok,  new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //getCurrTaChart().setTaParams(adapter.getTaIndexParamMap());
                        okCallback.update(adapter.getTaIndexParamMap());
                        flushAllViewToCurrentData();
                    }
                })
                .setNegativeButton(R.string.label_cancel, null).create();

        dialog.setCanceledOnTouchOutside(true);//使除了dialog以外的地方不能被点击
        dialog.show();
        //只用下面这一行弹出对话框时需要点击输入框才能弹出软键盘
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        //dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.NavStockBack:
                navStockBack();
                break;
            case R.id.NavStockForward:
                navStockForward();
                break;
            case R.id.TaIndexBack:
                navTaIndexBack();
                break;
            case R.id.TaIndexForward:
                navTaIndexForward();
                break;

            case R.id.TaIndexNameContainer:
                startParamDialog(getCurrTaChart().getTaIndexShortName(),
                        getCurrTaChart().getTaParamsList(),
                        new UpdateParamsCallBack() {
                            @Override
                            public void update(Hashtable<String, Integer> newParamMaps) {
                                getCurrTaChart().setTaParams(newParamMaps);
                            }
                        }
                    );
                break;
            case R.id.SmaDetails:
                startParamDialog(getString(R.string.param_sma_taindex_name),
                        getSmaParamsList(),
                        new UpdateParamsCallBack() {
                            @Override
                            public void update(Hashtable<String, Integer> newParamMaps) {
                                setSmaParamsList(newParamMaps);
                            }
                        }
                    );
                break;
            case R.id.BollbandDetails:
                startParamDialog(getString(R.string.param_bband_taindex_name),
                        getBollbandParamsList(),
                        new UpdateParamsCallBack() {
                            @Override
                            public void update(Hashtable<String, Integer> newParamMaps) {
                                setBollbandParamsList(newParamMaps);
                            }
                        }
                    );
                break;
            default:
                break;
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
        setContentView(R.layout.analysis_main);

        mMainChart          = (BOLLMASlipCandleStickChart) findViewById(R.id.bollKLineChart);
        mTaIndexRightBorder = (ImageView) findViewById(R.id.rightBorder);
        mTaIndexLeftBorder  = (ImageView) findViewById(R.id.leftBorder);

        mStockTaIndexFrame = (FrameLayout) findViewById(R.id.StockTaIndexFrame);
        mStockMainFrame    = (FrameLayout) findViewById(R.id.StockMainFrame);

        mNavTitleName      = (TextView) findViewById(R.id.NavTitleName);
        mNavTitleCode      = (TextView) findViewById(R.id.NavStockCode);

        mNavIntervalGroup       = (SegmentedGroup) findViewById(R.id.NavIntervalGroup);
        mNavIntervalDayButton   = (RadioButton) findViewById(R.id.NavDayRadioButton);
        mNavIntervalWeekButton  = (RadioButton) findViewById(R.id.NavWeekRadioButton);
        mNavIntervalMonthButton = (RadioButton) findViewById(R.id.NavMonthRadioButton);

        Button nav_back    = (Button) findViewById(R.id.NavStockBack);
        Button nav_forward = (Button) findViewById(R.id.NavStockForward);
        nav_back.setOnClickListener(this);
        nav_forward.setOnClickListener(this);

        Button ta_back = (Button) findViewById(R.id.TaIndexBack);
        ta_back.setOnClickListener(this);
        Button ta_forward = (Button) findViewById(R.id.TaIndexForward);
        ta_forward.setOnClickListener(this);

        View index_name_container = findViewById(R.id.TaIndexNameContainer);
        index_name_container.setOnClickListener(this);

        mStockOpenText   = (TextView) findViewById(R.id.StockOpenText);
        mStockHighText   = (TextView) findViewById(R.id.StockHighText);
        mStockDateText   = (TextView) findViewById(R.id.StockDateText);
        mStockCloseText  = (TextView) findViewById(R.id.StockCloseText);
        mStockLowText    = (TextView) findViewById(R.id.StockLowText);
        mStockVolumeText = (TextView) findViewById(R.id.StockVolumeText);
        mStockResultText = (TextView) findViewById(R.id.StockResultText);

        mStockMaDetailsText = (TextView) findViewById(R.id.SmaDetails);
        mStockMaDetailsText.setOnClickListener(this);
        mStockBollDetailsText = (TextView) findViewById(R.id.BollbandDetails);
        mStockBollDetailsText.setOnClickListener(this);

        mTaIndexShortName    = (TextView) findViewById(R.id.TaIndexShortName);
        mTaIndexDetail       = (TextView) findViewById(R.id.TaIndexDetail);
        mTaIndexParm     = (TextView) findViewById(R.id.TaIndexParms);

        mCurrStockCode  = getIntent().getStringExtra(ANALYSIS_CODE);
        if (mCurrStockCode == null) {
            finishAcitivity(getResources().getString(R.string.analysis_null_code_error));
            return;
        }

        String interval  = getIntent().getStringExtra(ANALYSIS_INTERVAL);
        if (interval == null) {
            finishAcitivity(getResources().getString(R.string.analysis_null_interval_error));
            return;
        }

        mCurrStock = DataProvider.getStock(this, mCurrStockCode);
        if (mCurrStock == null) {
            finishAcitivity(getResources().getString(R.string.analysis_invalid_code_error));
            return;
        }

        // SMA Param resource init
        mSmaShortPeriodName   = getString(R.string.param_ma_short_period);
        mSmaMediumPeriodName  = getString(R.string.param_ma_medium_period);
        mSmaLongPeriodName    = getString(R.string.param_ma_long_period);
        mSmaLongestPeriodName = getString(R.string.param_ma_longest_period);

        // BBAND Param resource init
        mBollbandMidmaPeriodName        = getString(R.string.param_bband_midma_period);;
        mBollbandUpSTDEVMultipleName    = getString(R.string.param_bband_upstdev_multiple);;
        mBollbandDownSTDEVMultipleName  = getString(R.string.param_bband_lowstdev_multiple);;

        //String inteval_name;
        if (Interval.DAILY.getTag().equalsIgnoreCase(interval)) {
            mCurrentInterval = Interval.DAILY;
            mNavIntervalDayButton.setChecked(true);
            //inteval_name = mNavIntervalDayButton.getText().toString();
        } else if (Interval.WEEKLY.getTag().equals(interval)) {
            mCurrentInterval = Interval.WEEKLY;
            mNavIntervalWeekButton.setChecked(true);
            //inteval_name = mNavIntervalWeekButton.getText().toString();
        } else if (Interval.MONTHLY.getTag().equalsIgnoreCase(interval)) {
            mCurrentInterval = Interval.MONTHLY;
            mNavIntervalMonthButton.setChecked(true);
            //inteval_name = mNavIntervalMonthButton.getText().toString();
        } else {
            finishAcitivity(getResources().getString(R.string.analysis_invalid_interval_error));
            return;
        }

        mMainDownloadingAnimation = AnimationUtils.loadAnimation(this, R.anim.download_rotate);
        mIndexDownloadingAnimation = AnimationUtils.loadAnimation(this, R.anim.download_rotate);

        mTaIndexFrameAnimateImage  = new ImageView(this);
        mTaIndexFrameAnimateImage.setImageResource(R.drawable.loading);
        mTaIndexFrameAnimateImage.setScaleType(ImageView.ScaleType.CENTER);
        mTaIndexFrameAnimateImage.setVisibility(View.VISIBLE);

        mMainFrameAnimateImage  = new ImageView(this);
        mMainFrameAnimateImage.setImageResource(R.drawable.loading);
        mMainFrameAnimateImage.setScaleType(ImageView.ScaleType.CENTER);
        mMainFrameAnimateImage.setVisibility(View.VISIBLE);

        mNavIntervalGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                Interval new_interval;
                //String   inteval_name;
                switch (checkedId) {
                    case R.id.NavDayRadioButton:
                        new_interval = Interval.DAILY;
                        //inteval_name = mNavIntervalDayButton.getText().toString();
                        break;
                    case R.id.NavWeekRadioButton:
                        new_interval = Interval.WEEKLY;
                        //inteval_name = mNavIntervalWeekButton.getText().toString();
                        break;
                    case R.id.NavMonthRadioButton:
                        new_interval = Interval.MONTHLY;
                        //inteval_name = mNavIntervalMonthButton.getText().toString();
                        break;
                    default:
                        return;
                }

                mCurrentInterval = new_interval;

                flushAllViewToCurrentData();
            }
        });

        TalibChartFactory.commonInitGridChart(mMainChart);
        TalibChartFactory.commonInitSlipStickChart(mMainChart);
        mMainChart.setOnDisplayCursorListener(new StockTachartCursorListener(true));
        mMainChart.setOnTouchListener(new StockTachartTouchListener());

//        ITalibChart taChart = TalibChartFactory.createTalibChart(TalibChartFactory.TaIndex.MACD, this);
//        taChart.setOnDisplayCursorListener(new StockTachartCursorListener());
//        taChart.getChartView().setOnTouchListener(new StockTachartTouchListener());
//        mTalibChartLists.add(taChart);

        mTalibChartLists = TalibChartFactory.createWholeTalibCharts(this);
        if (mTalibChartLists.size() > 0) {
            setCurrTaChart(0);
        }

        mBorderFlashAnimation = new AlphaAnimation(1, 0);
        mBorderFlashAnimation.setDuration(2000);
        mBorderFlashAnimation.setRepeatCount(0);
        mBorderFlashAnimation.setAnimationListener(new BorderAnimationListener());

        // refersh view on new data
        flushAllViewToCurrentData();
    }

    @Override
    protected void onResume() {
        /**
         * 设置为横屏
         */
        if(getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        super.onResume();
    }
}
